import { Card, Form, Select } from 'antd'
import React, { useEffect, useState } from 'react'
// redux相关
import { useAppDispatch, useAppSelector } from "@/app/hooks";
import { getCategory1Async, getCategory2Async, getCategory3Async, selectCategory, setCategory1Id, setCategory2Id, setCategory3Id } from './slice'
 
type LayoutType = Parameters<typeof Form>[0]['layout'];

export default function Category() {

  const [form] = Form.useForm();
  // 横向布局
  const [formLayout, setFormLayout] = useState<LayoutType>('inline');
  const formItemLayout = formLayout === 'horizontal' ? { labelCol: { span: 4 }, wrapperCol: { span: 14 }} : null;

  const dispatch = useAppDispatch();
  const category = useAppSelector(selectCategory)

  const { category1List, category2List, category3List } = category


  const getCategory2List = async (value: number) => {
    dispatch(setCategory1Id(value))
    await dispatch(getCategory2Async(value))
  };

  const getCategory3List = async (value: number) => {
    dispatch(setCategory2Id(value))
    await dispatch(getCategory3Async(value))
  };

  const getCategory3Id = (value: number) => {
    dispatch(setCategory3Id(value))
  }

  useEffect(() => {
    let getCategory1List = async () => {
      await dispatch(getCategory1Async())
    }
    getCategory1List();
  }, [])

  return (
    <div>
      <Card>
        <Form
          {...formItemLayout}
          layout={formLayout}
          form={form}
          initialValues={{ layout: formLayout }}
        >
          <Form.Item label="一级分类">
            <Select
              style={{ width: 200 }}
              placeholder='请选择'
              onChange={getCategory2List}
              options={category1List.map(category1 => ({ label: category1.name, value: category1.id }))}
            />
          </Form.Item>
          <Form.Item label="二级分类">
            <Select
              style={{ width: 200 }}
              placeholder='请选择'
              onChange={getCategory3List}
              options={category2List.map(category2 => ({ label: category2.name, value: category2.id }))}
            />
          </Form.Item>
          <Form.Item label="三级分类">
            <Select
              style={{ width: 200 }}
              placeholder='请选择'
              onChange={getCategory3Id}
              options={category3List.map(category3 => ({ label: category3.name, value: category3.id }))}
            />
          </Form.Item>
        </Form>
      </Card>
    </div>
  )
}
